package cn.information.dao;

import cn.information.bean.User;
import cn.information.utils.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UserDao {


    public void add(User user) {
        Connection conn = DButil.getConnection();
        String sql = "insert into user(uname,paswrd,purview) values(?,?,?)";
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUname());
            pstmt.setString(2, user.getPaswrd());
            pstmt.setInt(3, user.getPurview());
            pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<User> findAll() {
        Connection conn = DButil.getConnection ();
        String sql = "select * from user";
        Statement stmt = null;
        List<User> list =new ArrayList<>();
        try {
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
                User user = new User();
                user.setUname(rs.getString("uname"));
                user.setPaswrd(rs.getString("paswrd"));
                user.setPurview(rs.getInt("purview"));
                list.add(user);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            DButil.close(conn);
        }
        return list;
    }
}
